package com.xiaolei.lib.annotation.translators;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import com.xiaolei.lib.Activity.IActivity;
import com.xiaolei.lib.Activity.IFargment;
import com.xiaolei.lib.Activity.bean.AnnotationWrape;
import com.xiaolei.lib.annotation.setContentView;
import com.xiaolei.lib.callback.OnViewCreatedCallBack;
import com.xiaolei.lib.core.ITranslator;

import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;

public class setContentView_AutoWriteView_Translator implements ITranslator
{

	@Override
	public void execute(Field field, IActivity activity, AnnotationWrape annotation)
	{
		// TODO Auto-generated method stub

	}

	@Override
	public void execute(Method method, IActivity activity, AnnotationWrape annotation)
	{
		// TODO Auto-generated method stub

	}

	@Override
	public void execute(final Class<?> type,final IActivity activity, AnnotationWrape annotation)
	{
		setContentView bind = annotation.get(setContentView.class);
		int layout_id = bind.value();
		activity.setContentView(layout_id);
		if(IFargment.class.isInstance(activity))
		{
			((IFargment)activity).setOnCreateViewCallback(new OnViewCreatedCallBack()
			{
				@Override
				public void callback(View view, Bundle savedInstanceState)
				{
					Field fields[] = type.getDeclaredFields();
					Resources resources = activity.getResources();
					String defPackage = activity.getApplicationContext().getPackageName();
					for (Field field : fields)
					{
						String name = field.getName();
						int id = resources.getIdentifier(name, "id", defPackage);
						if (id == 0)
							continue;
						View view_sub = view.findViewById(id);
						if(!field.isAccessible())
						{
							field.setAccessible(true);
						}
						try
						{
							field.set(activity, view_sub);
						} catch (Exception e)
						{
							e.printStackTrace();
						}
					}
				}
			});
			return ;
		}else 
		{
			Field fields[] = type.getDeclaredFields();
			Resources resources = activity.getResources();
			String defPackage = activity.getApplicationContext().getPackageName();
			for (Field field : fields)
			{
				String name = field.getName();
				int id = resources.getIdentifier(name, "id", defPackage);
				if (id == 0)
					continue;
				View view = activity.findViewByID(id);
				if(!field.isAccessible())
				{
					field.setAccessible(true);
				}
				try
				{
					field.set(activity, view);
				} catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		}
	}

}
